from django.db import models

# Create your models here.


#自定义管理器
#重写默认objects管理器的all方法
#1、定义一个管理器的类
class BookInfoManager(models.Manager): #models.Manager 的本质就是objects

    def all(self):

        return super().filter(is_delete=False)

    def create_book(self, title, pub_date):
        # 创建模型类对象self.model可以获得模型类
        book = self.model()
        book.btitle = title
        book.bpub_date = pub_date
        book.bread = 0
        book.bcommet = 0
        book.is_delete = False
        # 将数据插入进数据表
        book.save()
        return book




class BookInfo(models.Model):

    #2、在模型类里指定管理器的类的对象
    book = BookInfoManager()

    btitle = models.CharField(max_length=20, verbose_name='名称')
    bpub_date = models.DateField(verbose_name='发布日期')
    bread = models.IntegerField(default=0, verbose_name='阅读量')
    bcomment = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')
    # image = models.ImageField(upload_to='upload', verbose_name="图书封面图片")

    class Meta:
        db_table = 'tb_books'  # 指明数据库表名
        verbose_name = '图书'
        verbose_name_plural = '图书'

    def __str__(self):
        return self.btitle

    #用来在后端列表里面自定义显示数据的格式
    def reads(self):

        return str(self.bread) + '个'

    #把显示数据的英文名称改成中文
    reads.short_description = '阅读量'


#定义英雄模型类HeroInfo
class HeroInfo(models.Model):
    GENDER_CHOICES = (
        (0, 'female'),
        (1, 'male')
    )
    hname = models.CharField(max_length=20, verbose_name='名称')
    hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')
    hcomment = models.CharField(max_length=200, blank=True, null=True, verbose_name='描述信息')
    hbook = models.ForeignKey(BookInfo, related_name="hero", verbose_name='图书')  # 外键
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_heros'
        verbose_name = '人物'
        verbose_name_plural = '人物'

    def __str__(self):
        return self.hname

    #显示关联模型中字段的数据
    def read(self):

        return self.hbook.bread

    # 把显示数据的英文名称改成中文
    read.short_description = '阅读量'